package com.xbongbong.workflow.service.help.saas;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.xbongbong.paas.domain.entity.PaasFormExplainEntity;
import com.xbongbong.paas.domain.entity.PaasStageEntity;
import com.xbongbong.paas.domain.entity.StageLogEntity;
import com.xbongbong.paas.domain.entity.StageProcessEntity;
import com.xbongbong.paas.enums.FieldTypeEnum;
import com.xbongbong.paas.enums.PlatFormEnum;
import com.xbongbong.paas.enums.StageTypeEnum;
import com.xbongbong.paas.field.FieldAttrEntity;
import com.xbongbong.paas.help.ProFormHelp;
import com.xbongbong.paas.model.PaasStageModel;
import com.xbongbong.paas.model.StageLogModel;
import com.xbongbong.paas.model.StageProcessModel;
import com.xbongbong.paas.service.DetailStageService;
import com.xbongbong.paas.service.stage.StageHandle;
import com.xbongbong.paas.service.stage.StageHandleFactory;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.pro.businesstage.pojo.dto.CommonJumpDTO;
import com.xbongbong.pro.enums.PaasStageEnum;
import com.xbongbong.pro.enums.SaasMarkEnum;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import com.xbongbong.pro.workflow.enums.WorkflowOperateEnum;
import com.xbongbong.saas.constant.BasicConstant;
import com.xbongbong.saas.toolbox.help.FastJsonHelper;
import com.xbongbong.workflow.pojo.Data;
import com.xbongbong.workflow.pojo.WorkflowTransferPOJO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;

/**
 * @ClassName WorkFlowSaasStageHelp
 * @Description 客户线索机会阶段跳转
 * @Author sunshaoxiang
 * @Date 2021/12/23 15:42
 * @Version 1.0
 **/

@Component
public class WorkFlowSaasStageHelp {

    private static final Logger LOG = LoggerFactory.getLogger(WorkFlowSaasStageHelp.class);

    @Resource
    private StageProcessModel stageProcessModel;
    @Resource
    private DetailStageService detailStageService;
    @Resource
    private StageHandleFactory stageHandleFactory;
    @Resource
    private ProFormHelp proFormHelp;
    @Resource
    private StageLogModel stageLogModel;
    @Resource
    private PaasStageModel paasStageModel;

    /**
     * 客户线索机会阶段跳转入工作流审批同意后操作
     * @param workflowTransferPOJO
     * @param stageAttr
     * @param fromStageEntity
     * @throws XbbException
     */
    public void workFlowStageJump(WorkflowTransferPOJO workflowTransferPOJO, String stageAttr, PaasStageEntity fromStageEntity) throws XbbException {
        try {
            boolean isNew = Objects.equals(workflowTransferPOJO.getOperate(), WorkflowOperateEnum.ADD.getType());
            String corpid = workflowTransferPOJO.getCorpid();
            Data newDataEntity = workflowTransferPOJO.getData();
            JSONObject newData = newDataEntity.getData();
            Long dataId = newDataEntity.getId();
            Long formId = newDataEntity.getFormId();
            Integer businessType = newDataEntity.getBusinessType();
            Integer saasMark = newDataEntity.getSaasMark();
            String toStageCode = FastJsonHelper.getStringOrDefaultFromFormData(newData, stageAttr, "");
            Long stageProcessId = FastJsonHelper.getLongOrDefaultFromFormData(newData, PaasStageEnum.STAGE_PROCESS_ID.getAttr(), BasicConstant.ZERO_LONG);
            StageProcessEntity stageProcessEntity;
            Long toStageId;
            PaasStageEntity toStageEntity;
            StageHandle stageHandle = stageHandleFactory.getStageHandle(SaasMarkEnum.SAAS.getCode(), businessType);
            //历史审批数据没有打入阶段id和阶段流程id,手动去拿
            if (Objects.equals(stageProcessId, BasicConstant.ZERO_LONG)) {
                stageProcessEntity = stageProcessModel.getByTransferVersion(corpid, formId, BasicConstant.ONE);
                toStageEntity = stageHandle.getByCode(corpid, formId, toStageCode);
            } else {
                stageProcessEntity = stageProcessModel.getByKey(stageProcessId, corpid);
                toStageId = FastJsonHelper.getLongOrDefaultFromFormData(newData, PaasStageEnum.STAGE_ID.getAttr(), BasicConstant.ZERO_LONG);
                toStageEntity = stageHandle.getByKey(toStageId, corpid);
            }
                CommonJumpDTO commonJumpDTO = new CommonJumpDTO(saasMark, businessType, formId, dataId);
                commonJumpDTO.setCorpid(corpid);
                commonJumpDTO.setFromStageType(Objects.isNull(fromStageEntity) || isNew ? StageTypeEnum.START_STAGE.getType() : fromStageEntity.getType());
                commonJumpDTO.setToStageType(toStageEntity.getType());
                commonJumpDTO.setFromStageEntity(Objects.isNull(fromStageEntity) || isNew ? null : fromStageEntity);
                commonJumpDTO.setToStageEntity(toStageEntity);
                commonJumpDTO.setStageProcessEntity(stageProcessEntity);
                commonJumpDTO.setStageAttr(stageAttr);
                commonJumpDTO.setFromApproval(BasicConstant.ONE);
                commonJumpDTO.setPlatform(PlatFormEnum.INTERNAL.getValue());
                commonJumpDTO.setUserId(workflowTransferPOJO.getUser().getUserId());
                commonJumpDTO.setIsNew(isNew);
                //用feign去调用阶段详情跳转方法
                detailStageService.commonJump(commonJumpDTO);
        } catch (Exception e) {
            LOG.error("WorkFlowSaasStageHelp.stageCommonJump出错:", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
        }
    }

    /**
     * Paas表单阶段跳转入工作流审批同意后操作
     *
     * @param workflowTransferPOJO
     * @throws XbbException
     */
    public void afterSaveStage(WorkflowTransferPOJO workflowTransferPOJO) throws XbbException{
        boolean isNew = Objects.equals(workflowTransferPOJO.getOperate(), WorkflowOperateEnum.ADD.getType());
        boolean hasStageField = false;
        String corpid = workflowTransferPOJO.getCorpid();
        Data newDataEntity = workflowTransferPOJO.getData();
        JSONObject newData = newDataEntity.getData();
        Long dataId = newDataEntity.getId();
        Long formId = newDataEntity.getFormId();
        Integer businessType = newDataEntity.getBusinessType();
        Integer saasMark = newDataEntity.getSaasMark();
        PaasFormExplainEntity explainEntity = proFormHelp.getExplainEntity(corpid, formId, businessType);
        List<FieldAttrEntity> fieldAttrEntities = JSON.parseArray(explainEntity.getExplains(), FieldAttrEntity.class);

        String stageAttr = "";
        for (FieldAttrEntity fieldAttrEntity : fieldAttrEntities) {
            if (Objects.equals(FieldTypeEnum.STAGE_THRUSTER.getType(), fieldAttrEntity.getFieldType()) && Objects.equals(BasicConstant.ONE, fieldAttrEntity.getIsOpen())){
                hasStageField = true;
                stageAttr = fieldAttrEntity.getAttr();
                break;
            }
        }
        //判断有没有阶段推进器字段
        if (hasStageField) {
            //跳转前的阶段需要从log表中实时去查一下，工作流的流转数据已经被更新过了，不能从那里拿
            StageLogEntity stageLogEntity = stageLogModel.getIsNowStage(corpid, formId, dataId);
            PaasStageEntity fromStageEntity = null;
            if ( !Objects.isNull(stageLogEntity)) {
                Long stageId = stageLogEntity.getStageId();
                fromStageEntity = paasStageModel.getByKey(stageId, corpid);
            }
            Long stageProcessId = FastJsonHelper.getLongOrDefaultFromFormData(newData, PaasStageEnum.STAGE_PROCESS_ID.getAttr(), BasicConstant.ZERO_LONG);
            StageProcessEntity stageProcessEntity = stageProcessModel.getByKey(stageProcessId, corpid);
            Long toStageId = FastJsonHelper.getLongOrDefaultFromFormData(newData, PaasStageEnum.STAGE_ID.getAttr(), BasicConstant.ZERO_LONG);
            PaasStageEntity toStageEntity = paasStageModel.getByKey(toStageId, corpid);
            //判断阶段是否发生阶段改变,发生阶段改变才需要跳转
            Long fromStageId = Objects.isNull(fromStageEntity) ? BasicConstant.ZERO_LONG : fromStageEntity.getId();
            boolean isChangeStage = !Objects.equals(toStageId, BasicConstant.ZERO_LONG) &&  !Objects.equals(toStageId, fromStageId);
            if (isChangeStage) {
                try {
                    //封装阶段跳转参数
                    CommonJumpDTO commonJumpDTO = new CommonJumpDTO(saasMark, businessType, formId, dataId);
                    commonJumpDTO.setCorpid(corpid);
                    commonJumpDTO.setFromStageType(Objects.isNull(fromStageEntity) || isNew ? StageTypeEnum.START_STAGE.getType() : fromStageEntity.getType());
                    commonJumpDTO.setToStageType(toStageEntity.getType());
                    commonJumpDTO.setFromStageEntity(Objects.isNull(fromStageEntity) || isNew ? null : fromStageEntity);
                    commonJumpDTO.setToStageEntity(toStageEntity);
                    commonJumpDTO.setStageProcessEntity(stageProcessEntity);
                    commonJumpDTO.setStageAttr(stageAttr);
                    commonJumpDTO.setFromApproval(BasicConstant.ONE);
                    commonJumpDTO.setPlatform(PlatFormEnum.INTERNAL.getValue());
                    commonJumpDTO.setUserId(workflowTransferPOJO.getUser().getUserId());
                    commonJumpDTO.setIsNew(isNew);
                    detailStageService.commonJump(commonJumpDTO);
                } catch (Exception e) {
                    LOG.error("WorkflowPaasDataStrategy.stageCommonJump出错:", e);
                    throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
                }
            }
        }
    }
}
